#!/bin/bash

# 检查是否安装了 Python 虚拟环境
if ! command -v python3 -m venv &> /dev/null; then
    echo "请先安装 Python 虚拟环境支持"
    echo "Ubuntu/Debian: sudo apt-get install python3-venv"
    echo "CentOS/RHEL: sudo yum install python3-venv"
    exit 1
fi

# 检查是否安装了 ImageMagick
if ! command -v convert &> /dev/null; then
    echo "未检测到 ImageMagick，这是 MoviePy 处理图像所必需的"
    echo "是否要安装 ImageMagick? (y/n)"
    read -r answer
    if [ "$answer" = "y" ] || [ "$answer" = "Y" ]; then
        # 检测操作系统并安装 ImageMagick
        if [ -f /etc/debian_version ]; then
            # Debian/Ubuntu
            sudo apt-get update
            sudo apt-get install -y imagemagick
        elif [ -f /etc/redhat-release ]; then
            # CentOS/RHEL
            sudo yum install -y imagemagick
        elif [ -f /etc/arch-release ]; then
            # Arch Linux
            sudo pacman -S imagemagick
        elif [ "$(uname)" == "Darwin" ]; then
            # macOS
            if command -v brew &> /dev/null; then
                brew install imagemagick
            else
                echo "请先安装 Homebrew，然后运行 'brew install imagemagick'"
                exit 1
            fi
        else
            echo "无法自动安装 ImageMagick，请手动安装后再运行此脚本"
            echo "安装指南: https://imagemagick.org/script/download.php"
            exit 1
        fi
    else
        echo "未安装 ImageMagick，应用可能无法正常工作"
        echo "请手动安装后再运行此脚本"
        echo "安装指南: https://imagemagick.org/script/download.php"
        exit 1
    fi
fi

# 检查虚拟环境是否存在，如果不存在则创建
if [ ! -d ".venv" ]; then
    echo "创建 Python 虚拟环境..."
    python3 -m venv .venv
fi

# 激活虚拟环境
source .venv/bin/activate

# 安装依赖
echo "安装项目依赖..."
pip install -r requirements.txt

# 运行应用
echo "启动应用..."
python app.py